package com.sc.ds.config;


import com.sc.ds.jdbc.DBUtil;
import org.apache.commons.lang3.StringUtils;
import org.flywaydb.core.Flyway;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import javax.annotation.PostConstruct;

public abstract class ShardingsphereDataSourceConfigurationAbstract extends DataSourceConfigurationAbstract {
    @Autowired
    private Environment environment;

    @PostConstruct
    public void createDefaultDB() {
        String dsNameStr = environment.getProperty("spring.shardingsphere.datasource.names");

        if(StringUtils.isNotBlank(dsNameStr)) {
            String[] dsNames = dsNameStr.split(",");
            if (dsNames != null && dsNames.length > 0) {
                for (String ds : dsNames) {
                    if (",".equals(ds) || StringUtils.isBlank(ds)) {
                        continue;
                    }

                    String url2 = environment.getProperty("spring.shardingsphere.datasource." + ds + ".url");
                    String username2 = environment.getProperty("spring.shardingsphere.datasource." + ds + ".username");
                    String password2 = environment.getProperty("spring.shardingsphere.datasource." + ds + ".password");
                    String driverClassName2 = environment.getProperty("spring.shardingsphere.datasource." + ds + ".driver-class-name");
                    String defaultUrl2 = url2.replace(ds,"mysql");

                    String dbName = url2.substring(url2.lastIndexOf("/") + 1,url2.indexOf("?"));
                    DBUtil.createDB(driverClassName2,defaultUrl2,username2,password2,dbName);

                    String baselineVersion = environment.getProperty("spring.flyway.baseline-version");
                    String baselineOnMigrate = environment.getProperty("spring.flyway.baseline-on-migrate");
                    Flyway flyway = Flyway.configure().baselineVersion(baselineVersion).baselineOnMigrate(Boolean.valueOf(baselineOnMigrate)).cleanOnValidationError(false).dataSource(url2, username2, password2).load();
                    flyway.migrate();
                }
            }
        }
    }
}
